package dev.marsh.hunter

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.content.FileProvider
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.TextView
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import java.io.File

class MainActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {
    var mRefreshLayout: SwipeRefreshLayout? = null
    var mListView: RecyclerView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mListView = findViewById(R.id.list)
        mListView?.adapter = WorkAdapter()
        mRefreshLayout = findViewById(R.id.refresh_layout)
        mRefreshLayout?.setOnRefreshListener(this)
    }

    override fun onResume() {
        super.onResume()
        invalidateOptionsMenu()
        onRefresh()
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onPrepareOptionsMenu(menu: Menu): Boolean {
        val menuItem = menu.findItem(R.id.action_settings)
        menuItem.isVisible = !checkSettings(this)
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_settings -> {
                goSettings(this)
                return true
            }
            R.id.action_start_service -> {
                startService(Intent(this, HunterService::class.java))
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onRefresh() {
        Observable.create(ObservableOnSubscribe<List<File>> {
            var files: List<File>? = null
            App.workDir.listFiles()?.let {
                files = it.toList()
            }
            it.onNext(files ?: emptyList())
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<List<File>>() {
                    override fun onComplete() {
                        // nothing
                    }

                    override fun onNext(t: List<File>) {
                        val workAdapter = mListView?.adapter as? WorkAdapter
                        workAdapter?.setData(t)
                        mRefreshLayout?.isRefreshing = false
                    }

                    override fun onError(e: Throwable) {
                        // nothing
                        mRefreshLayout?.isRefreshing = false
                    }
                })
    }
}

class WorkAdapter : RecyclerView.Adapter<WorkViewHolder>() {
    var mData: MutableList<File> = mutableListOf()

    fun setData(files: List<File>) {
        mData.clear()
        mData.addAll(files)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_work, parent, false)
        return WorkViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: WorkViewHolder, position: Int) {
        val file = mData[position]
        holder.name.text = file.name
        holder.share.setOnClickListener {
            val intent = Intent(Intent.ACTION_SEND)
            intent.type = "application/extension"
            val uri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                FileProvider.getUriForFile(it.context, "dev.marsh.hunter.fileProvider", file)
            } else {
                Uri.fromFile(file)
            }
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            it.context.startActivity(Intent.createChooser(intent, "Send file"))
        }
    }
}

class WorkViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val name: TextView = itemView.findViewById(R.id.name)
    val share: TextView = itemView.findViewById(R.id.share)
}
